
// @ts-ignore
import SparkMD5 from 'spark-md5'

export const getFileMD5 = (file:File) => {
    return new Promise((resolve, reject) => {
        let spark = new SparkMD5.ArrayBuffer()
        let fileReader = new FileReader()
        fileReader.onload = (e:any) => {
            spark.append(e.target.result)
            resolve(spark.end())
        }
        fileReader.onerror = () => {
            reject('读取文件Md5失败')
        }
        fileReader.readAsArrayBuffer(file)

    })
}

/**获得文件的md5，用来作为唯一索引  -  文件过大时，获取md5会很长很长时间，可以考虑用 文件名+文件最后修改时间+文件大小 做“唯一”标识*/
export const computeHash = (file: Blob) => {
    return new Promise<string>(async (resolve, reject) => {

        try {

            let spark = new SparkMD5.ArrayBuffer()
            let fileReader = new FileReader()
            fileReader.onload = (e:any) => {
                spark.append(e.target.result)
                resolve(spark.end())
            }
            fileReader.onerror = () => {
                reject('读取文件Md5失败')
            }
            fileReader.readAsArrayBuffer(file);
             // reader.readAsArrayBuffer(files[files.length-1]);
             // reader.readAsArrayBuffer();

        } catch (error) {
            reject(error)
        }
    })
}




